package com.sheep.jucdemo.part7.part7_2;

import java.util.concurrent.*;

/**
 * @Date 2022/5/9 22:50
 * @Created by sheep
 */
public class Test7_2_2 {

    // 篮子，能够容纳3个苹果
    BlockingQueue<String> blockingQueue = new LinkedBlockingQueue<String>(3);

    // 生产苹果，放入篮子
    public void produce() throws InterruptedException{
        // put方法放入一个苹果，若basket满了，等到basket有位置
        blockingQueue.put("An apple");
    }
    // 消费苹果，从篮子中取走
    public String consume() throws InterruptedException{
        // get方法取出一个苹果，若basket为空，等到basket有苹果为止
        return blockingQueue.take();
    }

    public int getAppleNumber(){
        return blockingQueue.size();
    }


    //　测试方法
    public static void testBasket() {
        // 建立一个装苹果的篮子
        final Test7_2_2 test = new Test7_2_2();
        // 定义苹果生产者
        class Producer implements Runnable {
            public void run() {
                try {
                    while (true) {
                        // 生产苹果
                        System.out.println("生产者准备生产苹果：" + System.currentTimeMillis());
                        test.produce();
                        System.out.println("生产者生产苹果完毕：" + System.currentTimeMillis());
                        System.out.println("生产完后有苹果：" + test.getAppleNumber()+"个");
                        // 休眠300ms
                        Thread.sleep(300);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        // 定义苹果消费者
        class Consumer implements Runnable {
            public void run() {
                try {
                    while (true) {
                        // 消费苹果
                        System.out.println("消费者准备消费苹果：" + System.currentTimeMillis());
                        test.consume();
                        System.out.println("消费者消费苹果完毕：" + System.currentTimeMillis());
                        System.out.println("消费完后有苹果：" + test.getAppleNumber() + "个");
                        // 休眠1000ms
                        Thread.sleep(1000);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

        ExecutorService service = Executors.newCachedThreadPool();
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        ExecutorService executorService1 = Executors.newFixedThreadPool(10);
        ExecutorService executorService2 = Executors.newCachedThreadPool();
        Producer producer = new Producer();
        Consumer consumer = new Consumer();
        service.submit(producer);
        service.submit(consumer);
        // 程序运行10s后，所有任务停止
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        service.shutdownNow();
    }

    public static void main(String[] args) {
        Test7_2_2.testBasket();
    }

}
